package com.dx.wx.controller;

import com.dx.wx.service.DxMediaService;
import com.dx.wx.service.DxWxAppService;
import com.ejlchina.data.Mapper;
import com.yf.annotation.IgnoreAuth;
import com.yf.response.R;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/dx/media")
public class ApiDxMediaController {

    @Autowired
    private DxMediaService dxMediaService;

    @IgnoreAuth
    @GetMapping("/download")
    public void download(String mediaId,HttpServletResponse response){
        dxMediaService.download(mediaId,response);
    }

    @PostMapping("/upload")
    @IgnoreAuth
    public R upload(@RequestParam MultipartFile file){
        Mapper mapper = dxMediaService.upload(file);
        return R.ok(mapper.toString());
    }

    @Autowired
    private DxWxAppService dxWxAppService;

    @PostMapping("/ocr/upload")
    @IgnoreAuth
    public R ocrUpload(@RequestParam MultipartFile file){
        Mapper mapper = dxMediaService.upload(file);
        Mapper ocrMapper = dxWxAppService.orc(file);
        Map res = new HashMap();
        res.put("mediaId",mapper.getString("mediaId"));
        StringBuffer ocr = new StringBuffer();
        System.out.println(ocrMapper.toString());
        if(ocrMapper.getArray("items")!=null){
            ocrMapper.getArray("items").forEach((index,data)->{
                String tem =  data.toMapper().getString("text");
               if( tem.matches("^\\d*$")){
                    ocr.append(tem);
               }
            });
        }

        res.put("ocr",ocr.toString());
        //OCR识别
        return R.ok(res);
    }

}
